package cn.tedu.lock;

import java.util.concurrent.Exchanger;

/**
 * 案例: 生产消费
 * 生产者将商品交换给消费者
 * 消费者将财务交换给生产者
 */
public class ExchangerDemo {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(new Producer(exchanger)).start();
        new Thread(new Consumer(exchanger)).start();
    }
}

class Producer implements Runnable {
    private Exchanger<String> exchanger;

    public Producer(Exchanger<String> exchanger) {
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            String info = "商品";
            // 生产者将商品交换给消费者, 同时应该收到消费者交换过来的财物
            String msg = exchanger.exchange(info);
            System.out.println("生产者收到了消费者换过来的: " + msg);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private Exchanger<String> exchanger;

    public Consumer(Exchanger<String> exchanger) {
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            String info = "财物";
            // 消费者将财物交换给生产者, 同时应该收到生产者交换过来的商品
            String msg = exchanger.exchange(info);
            System.out.println("消费者收到了生产者换过来的: " + msg);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
    }
}